package com.example.mvcdemo.login

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.widget.Toast
import com.example.mvcdemo.R
import com.example.mvcdemo.entity.UserBean
import com.example.mvcdemo.list.WeChatOfficialAccountListActivity
import kotlinx.android.synthetic.main.activity_main.*

class LoginActivity : AppCompatActivity(),
    LoginListener {
    override fun onLoginSuccess() {
        Toast.makeText(this, "登录成功", Toast.LENGTH_SHORT).show()
        tv_login.isEnabled = true
        this.startActivity(Intent(this, WeChatOfficialAccountListActivity::class.java))
    }

    override fun onloginFail() {
        Toast.makeText(this, "登录失败", Toast.LENGTH_SHORT).show()
        tv_login.isEnabled = true
    }

    override fun onLoading() {
        Toast.makeText(this, "加载中", Toast.LENGTH_SHORT).show()
        //禁止按钮点击,防止重复提交
        tv_login.isEnabled = false
    }

    /**
     * 持有model的对象
     */
    private val userModel by lazy {
        LoginModel()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        initListener()
    }

    private fun initListener() {
        tv_login.setOnClickListener {
            //进行登录
            toLogin()
        }
    }

    private fun toLogin() {
        //做登录的逻辑处理
        var account = edit_account.text.toString()
        val password = edit_password.text.toString()
        //检查账号格式是否正确
        if (TextUtils.isEmpty(account)) {
            Toast.makeText(this, "账号输入错误", Toast.LENGTH_SHORT).show()
            return
        }
        //检查密码长度
        if (password.length < 5) {
            Toast.makeText(this, "密码长度不得少于五位", Toast.LENGTH_SHORT).show()
            return
        }
        //进行登录,此操作为异步
        userModel.doLogin(
            this,
            UserBean(account, password)
        )
    }
}
